package com.ls.controller;

import com.ls.annotation.LoginRequired;
import com.ls.entity.Event;
import com.ls.entity.Page;
import com.ls.entity.User;
import com.ls.event.EventProducer;
import com.ls.service.FollowService;
import com.ls.service.UserService;
import com.ls.util.CommunityConstant;
import com.ls.util.CommunityUtil;
import com.ls.util.UserContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * @author ls
 * @date 2021/1/9
 **/
@Controller
public class FollowController implements CommunityConstant {

    @Autowired
    private FollowService followService;

    @Autowired
    private UserContextHolder userContextHolder;

    @Autowired
    private UserService userService;

    @Autowired
    private EventProducer eventProducer;

    /**
     * 关注
     *
     * @param entityType 实体类型
     * @param entityId   实体Id
     * @return
     */
    @LoginRequired
    @PostMapping("/follow")
    @ResponseBody
    public String follow(int entityType, int entityId) {
        User user = userContextHolder.getUser();

        followService.follow(user.getId(), entityType, entityId);

        // 触发关注事件
        Event event = new Event()
                .setTopic(TOPIC_FOLLOW)
                .setUserId(user.getId())
                .setEntityType(entityType)
                .setEntityId(entityId)
                .setEntityUserId(entityId);
        eventProducer.fireEvent(event);

        return CommunityUtil.getJSONString("已关注!");
    }

    /**
     * 取消关注
     *
     * @param entityType 实体类型
     * @param entityId   实体Id
     * @return
     */
    @LoginRequired
    @PostMapping("/unFollow")
    @ResponseBody
    public String unFollow(int entityType, int entityId) {
        User user = userContextHolder.getUser();

        followService.unFollow(user.getId(), entityType, entityId);

        return CommunityUtil.getJSONString("已取消关注!");
    }

    @GetMapping("/followees/{userId}")
    public String followees(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.queryUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }
        model.addAttribute("user", user);
        page.setPageSize(5);
        page.setPath("/followees/" + userId);
        page.setTotalCount((int) followService.getFolloweeCount(userId, ENTITY_TYPE_USER));

        List<Map<String, Object>> followees = followService.getFollowees(userId, page.getStartIndex(), page.getPageSize());
        if (followees != null) {
            for (Map<String, Object> map : followees) {
                User u = (User) map.get("user");
                map.put("hasFollowed", hasFollowed(u.getId()));
            }
        }
        model.addAttribute("followees", followees);

        return "site/followee";
    }

    @GetMapping("/followers/{userId}")
    public String followers(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.queryUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }
        model.addAttribute("user", user);
        page.setPageSize(5);
        page.setPath("/followers/" + userId);
        page.setTotalCount((int) followService.getFollowerCount(ENTITY_TYPE_USER, userId));

        List<Map<String, Object>> followers = followService.getFollowers(userId, page.getStartIndex(), page.getPageSize());
        if (followers != null) {
            for (Map<String, Object> map : followers) {
                User u = (User) map.get("user");
                map.put("hasFollowed", hasFollowed(u.getId()));
            }
        }
        model.addAttribute("followers", followers);

        return "site/follower";
    }

    /**
     * 返回登录用户是否关注 userId 用户
     *
     * @param userId
     * @return
     */
    boolean hasFollowed(int userId) {
        if (userContextHolder.getUser() == null) {
            return false;
        }
        return followService.hasFollowed(userContextHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
    }

}
